<template>
	<view class="container">
		<view class="header">
			<view class="logo-container">
				<text class="app-title">སྐད་ལྔ་ཤན་སྦྱར་ཚིག་མཛོད་ཀུན་གསལ་མེ་ལོང་།</text>
				<text class="app-title">五体清文鉴词典</text>
			</view>
			<image class="header-image" src="/static/wtqwj.png" mode="aspectFit"></image>
		</view>

		<!-- 搜索控制区域 -->
		<view class="search-control">
			<view class="search-box">
				<uni-easyinput v-model="searchKeyword"
					placeholder="བོད་ཡིག་དང་རྒྱ་ཡིག སོག་ཡིག མན་ཡིག ཡུ་གུར་་ཡི་གེ་བཅས་སྐད་རིགས་ལྔ་གཏགས་ཆོག"
					prefixIcon="search" :inputBorder="false" @confirm="handleSearch">
					<template v-slot:right>
						<button class="search-btn" @click="handleSearch">འཚོལ་བཤེར།</button>
					</template>
				</uni-easyinput>
			</view>
		</view>

		<!-- 搜索结果展示区域 -->
		<search-results :results="filteredResults" :active-collapse.sync="activeCollapse"
			:active-tibetan.sync="activeTibetan" :show-empty-state="showEmptyState" :empty-text="emptyText"
			:has-more="hasMore" :is-loading="isLoading" @tibetan-change="handleTibetanCollapseChange" />

		<!-- 底部操作栏 -->
		<view class="footer-controls">
			<uni-file-picker v-if="!db" v-model="dbFiles" :limit="1" file-mediatype="all" mode="button"
				:auto-upload="false" @select="handleFileSelect">
				<button class="import-btn" size="mini">
					<uni-icons type="upload" size="16" /> 导入数据库
				</button>
			</uni-file-picker>

			<text>版本：web2.2.1</text>
			<a href="/static/WTQYJ.pdf" style="color: #3498db !important; text-decoration: none !important;"
				target="_blank" rel="noopener noreferrer"
				onclick="window.open(this.href, 'PDFViewer', 'width=1200,height=800,scrollbars=yes'); return false;">
				PDF
			</a>
			<text class="about-btn" @click="showAbout">介绍</text>
			<text>数据版本：2025-5-21</text>
		</view>
		<!-- 简介弹窗 -->
		<view v-if="showPopup" class="popup-mask" @click="closeAbout">
			<view class="popup-content" @click.stop>
				<about />
				<button class="close-btn" @click="closeAbout">X</button>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="isLoading" class="loading-mask">
			<view class="loading-box">
				<uni-icons type="spinner-cycle" size="48" color="#3498db" class="loading-icon" />
				<text>加载中...</text>
			</view>
		</view>
	</view>
</template>


<script>
	import SearchResults from '@/components/SearchResults.vue';
	import about from '@/pages/index/about.vue';
	import {
		initializeSQL,
		loadDefaultDatabase,
		processDatabase
	} from '@/utils/LoadDatabase';
	import {
		tibetanSort,
		generalSort
	} from '@/utils/Sort';
	const LANG_RANGES = {
		'藏': /[\u0F00-\u0FFF]/,
		'蒙': /[\u1800-\u18AF]/,
		'满': /[a-zA-Z]/,
		'维': /[\u0600-\u06FF]/,
		'汉': /[\u4E00-\u9FA5]/
	};

	export default {
		components: {
			SearchResults,
			about
		},
		data() {
			return {
				showPopup: false,
				searchKeyword: '',
				englishWordSearchPreference: null,
				dbFiles: [],
				dbData: [],
				SQL: null,
				db: null,
				searchExecuted: false,
				isLoading: false,
				activeCollapse: [],
				activeTibetan: [],
				debounce: null,
				currentPage: 1,
				pageSize: 260,
				hasMore: true,
				currentWhereClause: '',
				progressInterval: null,
				debounceLoad: null,
				debounceSearch: null // 新增防抖控制
			};
		},
		watch: {
			searchKeyword(newVal) {
				if (newVal === '') {
					this.searchExecuted = false;
					this.dbData = [];
				}
			}
		},
		computed: {
			filteredResults() {
				return this.searchExecuted ? this.dbData : [];
			},
			showEmptyState() {
				return this.searchExecuted && !this.dbData.length;
			},
			emptyText() {
				return this.isSearchMode ?
					'གནས་སྐབས་ཟླ་སྒྲིག་མཇུག་འབྲས་མེད། ' :
					'གཞི་གྲངས་མཛོད་ཁ་སྣོན་བྱས་མེད།';
			},
			isSearchMode() {
				return this.searchKeyword.length > 0;
			}
		},
		async created() {
			this.SQL = await initializeSQL();
			await loadDefaultDatabase.call(this);
		},
		methods: {
			// 弹窗控制方法
			showAbout() {
				this.showPopup = true;
			},
			closeAbout() {
				this.showPopup = false;
			},
			// 触底加载
			onReachBottom() {
				if (this.debounceLoad) clearTimeout(this.debounceLoad);

				this.debounceLoad = setTimeout(() => {
					if (this.hasMore && !this.isLoading && this.searchExecuted) {
						this.currentPage++;
						this.handleLoadMore();
					}
				}, 300);
			},

			async handleSearch() {
				if (!this.searchKeyword.trim()) {
					this.searchExecuted = false;
					this.dbData = [];
					uni.showToast({
						title: 'གནད་ཚིག་འཚོལ་བཤེར་གནང་རོགས།',
						icon: 'none'
					});
					return;
				}

				try {
					// 重置状态
					this.englishWordSearchPreference = null;
					this.searchExecuted = false;
					this.currentPage = 1;
					this.hasMore = true;
					this.dbData = [];

					this.isLoading = true;

					this.showConsoleProgress();
					console.time('搜索耗时');

					const langType = await this.detectInputType(this.searchKeyword);
					const searchFields = this.getSearchFields(langType);

					const safeKeyword = this.searchKeyword
						.replace(/[^\u0F00-\u0FFF\u1800-\u18AF\u0600-\u06FF\u4E00-\u9FA5a-zA-Z\s]/g, '')
						.replace(/\s+/g, ' ')
						.trim();

					this.currentWhereClause = searchFields
						.map(f => f === 'མན་ཇུ།满语' ?
							`LOWER(${f}) LIKE '%${safeKeyword.toLowerCase()}%'` :
							`${f} LIKE '%${safeKeyword}%'`
						).join(' OR ');

					await this.executeQuery();

					// 只有在成功执行后才标记为已搜索
					this.searchExecuted = true;
				} finally {
					this.clearConsoleProgress();
					console.timeEnd('搜索耗时');
					this.isLoading = false;
				}
			},

			async executeQuery() {
				try {
					const offset = (this.currentPage - 1) * this.pageSize;
					const query =
						`SELECT * FROM '五体' WHERE ${this.currentWhereClause} LIMIT ${offset}, ${this.pageSize}`;

					console.log(`\x1b[36m执行SQL: ${query}\x1b[0m`);
					const result = this.db.exec(query);

					const newData = result[0]?.values.map(row =>
						result[0].columns.reduce((obj, col, index) => {
							obj[col] = row[index];
							return obj;
						}, {})
					) || [];

					const langType = await this.detectInputType(this.searchKeyword);
					const searchFields = this.getSearchFields(langType);

					if (langType === '藏') {
						console.log('\x1b[33m正在应用藏文排序算法...\x1b[0m');
						tibetanSort(newData, this.searchKeyword);
					} else {
						generalSort(newData, langType, this.searchKeyword, searchFields[0]);
					}

					this.hasMore = newData.length >= this.pageSize;
					this.dbData = [...this.dbData, ...newData];
					console.log(`\x1b[32m获取到 ${newData.length} 条结果 (总计: ${this.dbData.length})\x1b[0m`);
				} catch (error) {
					console.error('\x1b[31m查询错误:\x1b[0m', error);
					throw error;
				}
			},

			async handleLoadMore() {
				if (!this.hasMore || this.isLoading || !this.searchExecuted) return;

				try {
					this.isLoading = true;
					await this.executeQuery();
				} catch (error) {
					this.currentPage--;
					console.error('加载更多失败:', error);
				} finally {
					this.isLoading = false;
				}
			},

			async detectInputType(text) {
				if (/[\u1800-\u18AF]/.test(text)) return '蒙';
				if (/[\u0F00-\u0FFF]/.test(text)) return '藏';
				if (/^[a-zA-Z]+$/.test(text)) {
					if (this.englishWordSearchPreference) return this.englishWordSearchPreference;
					const {
						confirm
					} = await new Promise((resolve, reject) => {
						uni.showModal({
							title: 'སྐད་རིགས་འདེམས་པ།',
							content: 'ཞིབ་བཤེར་བྱས་ནས་སྒྲོམ་གཞིར་གཏགས་པ་ནི་ལ་ཏིང་ཡི་གེ་ཡིན།མན་ཡིག་གདམ་མམ་སོག་ཡིག་གདམ།',
							confirmText: 'ཡུ་གུར།',
							cancelText: 'མན་ཇུ།',
							success: res => resolve(res),
							error: res => reject(res)
						});
					});
					this.englishWordSearchPreference = (confirm ? '维' : '满');
					return this.englishWordSearchPreference;
				}

				const cleanText = text.replace(/[^\u0F00-\u0FFF\u1800-\u18AF\u0600-\u06FF\u4E00-\u9FA5a-zA-Z]/g, '');
				const langPriority = ['蒙', '藏', '维', '满', '汉'];
				for (const lang of langPriority) {
					if (LANG_RANGES[lang].test(cleanText)) return lang;
				}
				return '汉';
			},

			getSearchFields(langType) {
				const FIELD_MAP = {
					'藏': ['བོད་ཡིག藏语'],
					'蒙': ['སོག་ཡིག蒙古语'],
					'满': ['མན་ཇུ།满语'],
					'维': ['ཡུ་གུར་ལ་ཏིང་སྒྱུར་འབྲི།维吾尔语拉丁转写'],
					'汉': ['རྒྱ་ཡིག汉语', 'ཟོར་ཡང་ཡིག་གཟུགས།简体字']
				};
				return FIELD_MAP[langType] || [];
			},

			async handleFileSelect(e) {
				try {
					this.isLoading = true;
					const file = e.tempFiles[0].file;
					const buffer = await this.readFileAsBuffer(file);
					await processDatabase.call(this, buffer);
					uni.showToast({
						title: '数据库加载成功'
					});
				} catch (error) {
					this.showError('文件加载失败');
				} finally {
					this.isLoading = false;
				}
			},

			readFileAsBuffer(file) {
				return new Promise((resolve, reject) => {
					const reader = new FileReader();
					reader.onload = () => resolve(reader.result);
					reader.onerror = reject;
					reader.readAsArrayBuffer(file);
				});
			},

			showError(message, showToast = true) {
				if (showToast) {
					uni.showToast({
						title: message,
						icon: 'none',
						duration: 3000
					});
				}
				console.error(message);
			},

			handleTibetanCollapseChange({
				index,
				value
			}) {
				this.$set(this.activeTibetan, index, value.detail[0]);
				if (this.debounce) clearTimeout(this.debounce);

				this.debounce = setTimeout(() => {
					this.$nextTick(() => {
						const mainCollapse = this.$refs.searchResults?.$refs.mainCollapse?.[index];
						if (mainCollapse) {
							mainCollapse.onResize();
							setTimeout(() => mainCollapse.onResize(), 300);
						}
					});
				}, 50);
			},

			showConsoleProgress() {
				let progress = 0;
				const progressChars = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];

				this.progressInterval = setInterval(() => {
					const frame = progressChars[progress++ % progressChars.length];
					console.log(`\x1b[34m${frame} 正在搜索藏文数据库... ${progress}%\x1b[0m`);
					if (progress >= 100) progress = 0;
				}, 150);
			},

			clearConsoleProgress() {
				if (this.progressInterval) {
					clearInterval(this.progressInterval);
					console.log('\x1b[32m✓ 搜索完成\x1b[0m');
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	.container {
		height: 90vh;
		display: flex;
		flex-direction: column;
		background: #f5f7fa;
	}

	.header {
		height: 20vh;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 40rpx;
		background: linear-gradient(135deg, #2c3e50, #3498db);
		color: white;
		position: relative;

		.logo-container {

			display: flex;
			flex-direction: column;
			/* 改变主轴为垂直方向 */
			align-items: flex-start;
			/* 可选：根据需求调整横向对齐方式 */
			gap: 30rpx;
			/* 子元素之间的间距 */

			.app-title {
				font-family: 'Jomolhari', sans-serif; // 使用新的字体名称
				font-size: 44rpx;
				font-weight: 500;
			}

		}

		.system-info {
			display: flex;
			flex-direction: column;
			gap: 10rpx;
			font-size: 28rpx;
			opacity: 0.9;
		}
	}

	.header-image {
		max-width: 100%;
		max-height: 100%;
		position: absolute;
		right: 40rpx;
		width: 300rpx;
		height: 300rpx;
		padding-top: 0;
		object-fit: contain;
	}

	.search-control {
		padding: 3rpx 10rpx;
		display: flex;
		gap: 40rpx;
		background: #f5f7fa;

		.search-box {
			flex: 1;
			border: 1rpx solid #dcdcdc;
			border-radius: 50rpx;
			overflow: hidden;
			display: flex;
			align-items: center;
			padding: 8rpx 16rpx;
			background-color: #f9f9f9;
			transition: border-color 0.3s ease, box-shadow 0.3s ease;

			&:focus-within {
				border-color: #3498db;
				box-shadow: 0 4rpx 12rpx rgba(52, 152, 219, 0.3);
			}

			.search-btn {
				background: #3498db;
				color: white;
				padding: 0 30rpx;
				border-radius: 50rpx;

				&:hover {
					background: #2980b9;
				}

				&:active {
					background: #1e6f9f;
				}
			}
		}
	}

	.footer-controls {
		position: fixed;
		/* 固定在页面底部 */
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx 40rpx;
		display: flex;
		justify-content: space-between;
		border-top: 1rpx solid #eee;
		background: white;
		z-index: 1000;
		/* 确保在其他内容之上 */

		.import-btn {
			background: #27ae60;
			color: white;
		}

		display: flex;
		align-items: center;
		gap: 30rpx;

		.about-btn {
			color: #3498db;
			cursor: pointer;
		}
	}

	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0.8);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;

		.loading-box {
			padding: 40rpx;
			background: white;
			border-radius: 16rpx;
			box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
			display: flex;
			flex-direction: column;
			align-items: center;

			text {
				margin-top: 20rpx;
				color: #666;
			}
		}
	}

	.loading-icon {
		animation: spin 1s linear infinite;
	}

	@keyframes spin {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	.popup-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	.popup-content {
		width: 75%;
		height: 75%;
		background: #fff;
		border-radius: 16rpx;
		padding: 40rpx;
		display: flex;
		flex-direction: column;
		position: relative;

		.close-btn {
			position: absolute;
			bottom: 15rpx;
			right: 15rpx;
			padding: 6rpx 18rpx;
			font-size: 24rpx;
			background: #3498db;
			color: white;
			border-radius: 6rpx;
			line-height: 1.2;
			width: 120rpx;
			height: 60rpx;
			box-sizing: border-box;
		}
	}
</style>